var crypto = require("../utils/crypto");

var tokens = {};
var users = {};
var TOKEN_PRI_KEY = "^!@#$%^&";

exports.createToken = function(userId, lifeTime){
	var token = users[userId];
	if(token != null){
		this.delToken(token);
	}
	if (lifeTime == null) {
		lifeTime = 5000;
	}
	var time = Date.now();
	token = crypto.md5(userId + TOKEN_PRI_KEY+ time);
	tokens[token] = {
		userId: userId,
		time: time,
		lifeTime: lifeTime
	};
	users[userId] = token;
	return token;
};

exports.delUserToken = function(userId){
	var token = exports.getToken(userId);
	exports.delToken(token);
};

exports.delToken = function(token){
    var info = tokens[token];
    if(info != null){
        tokens[token] = null;
        users[info.userId] = null;
    }
};

exports.getToken = function(userId){
	return users[userId];
};

exports.isTokenValid = function(token){
    var info = tokens[token];
    if(info == null){
        return false;
    }
    if(info.time + info.lifeTime < Date.now()){
        return false;
    }
    return true;
};

exports.getUserID = function(token){
	return tokens[token].userId;
};



